"""
初始化MongoDB索引
"""

from motor.motor_asyncio import AsyncIOMotorDatabase
import logging

logger = logging.getLogger(__name__)


async def init_template_indexes(db: AsyncIOMotorDatabase):
    """初始化模板集合的索引"""
    try:
        templates_collection = db.templates

        # 创建索引
        await templates_collection.create_index("id", unique=True)
        await templates_collection.create_index("category")
        await templates_collection.create_index("isPublic")
        await templates_collection.create_index("authorId")
        await templates_collection.create_index("tags")
        # 不使用文本索引，避免语言设置冲突
        # await templates_collection.create_index([("name", "text"), ("description", "text")])
        await templates_collection.create_index([("usageCount", -1)])
        await templates_collection.create_index([("createdAt", -1)])

        logger.info("Templates collection indexes created successfully")

    except Exception as e:
        logger.error(f"Failed to create template indexes: {e}")
        raise


async def init_all_indexes(db: AsyncIOMotorDatabase):
    """初始化所有集合的索引"""
    await init_template_indexes(db)
    logger.info("All indexes initialized successfully")
